<template>
  <div class="login-container">
    <div class="login-form">
      <h1 v-text="siteInfo.siteName"></h1>
      <div class="form-input-material">
        <input
          v-model="formData.username"
          class="form-control-material"
          placeholder=" "
          @keydown.enter="handleSubmit"
        />
        <label>用户名</label>
      </div>
      <div class="form-input-material">
        <input
          class="form-control-material"
          type="password"
          v-model="formData.password"
          placeholder=" "
          autocomplete="off"
          @keydown.enter="handleSubmit"
        />
        <label>密码</label>
      </div>
      <button class="btn login-btn btn-primary btn-pulse" @click="handleSubmit">
        登录
      </button>
    </div>

    <span class="copy-right"
      >©2021-2022 WebPrototype Project, All Rights Reserved.</span
    >
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { login } from "@/api/user";
export default {
  data() {
    return {
      formData: {
        username: "",
        password: ""
      },
      required: {
        username: "请输入用户名",
        password: "请输入密码"
      }
    };
  },
  methods: {
    ...mapActions({
      changeUserInfo: "global/login",
      setToken: "global/setToken"
    }),
    async handleSubmit(e) {
      let isOk = true;
      Object.keys(this.required).forEach((item) => {
        if (!this.formData[item]) {
          this.$notification.error({
            message: this.required[item]
          });
          isOk = false;
        }
      });

      if (!isOk) return;
      try {
        const { code, data, msg } = await login(this.formData);
        if (code === 200) {
          this.$notification.success({
            message: "登录成功"
          });
          await this.changeUserInfo(data);
          await this.setToken(data.token);
          this.$router.push("/");
        }
      } catch (error) {}
    }
  },
  computed: {
    ...mapGetters(["siteInfo"])
  }
};
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("../../assets/images/login-background.jpg");
  .login-form {
    width: 350px;
    border-radius: 10px;
    padding: 30px;
    background-color: rgba(255, 255, 255, 0.6);
    .form-input-material,
    .form-check {
      margin: 30px 0 !important;
    }
  }

  .login-btn {
    margin: 0;
    width: 100%;
    padding: 10px 0;
  }

  .copy-right {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translate(-50%, 0);
  }
}
</style>
